#include <QtGui>
#include <QPalette>
#include <QColor>
#include <QVBoxLayout>
#include <QPixmap>
#include <qmath.h>
#include "analogiclock.h"
#include "digitalclock.h"

AnalogiClock::AnalogiClock(QWidget *parent): QWidget(parent)
{
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(100);


    cycle = floor(QTime::currentTime().msec() / 100.0);

    this->setObjectName(tr("ANALOGIC CLOCK"));

    //    resize(350,350);
}

void AnalogiClock::paintEvent(QPaintEvent *)
{
    static const QPoint hourHand[4] = {
        QPoint(3, 8),
        QPoint(-3, 8),
        QPoint(-3, -70),
         QPoint(3, -70)
    };
    static const QPoint minuteHand[4] = {
        QPoint(2, 8),
        QPoint(-2, 8),
        QPoint(-2, -95),
        QPoint(2, -95)
    };
    static const QPoint secondHand[3] = {
        QPoint(2, 8),
        QPoint(-2, 8),
        QPoint(0, -100)
    };

    QColor hourColor(127, 0, 127);
    QColor minuteColor(0, 127, 127, 191);
    QColor secondColor(0,0,0);

    int side = qMin(width(), height());
    QTime time = QTime::currentTime();

    QPainter painter(this);

    QPalette p(palette());
    p.setColor(QPalette::Background, Qt::white);
    this->setAutoFillBackground(true);
    this->setPalette(p);

    painter.setRenderHint(QPainter::Antialiasing);
    painter.translate(width() / 2, height() / 2);
    painter.scale(side / 200.0, side / 200.0);

    painter.setPen(Qt::NoPen);
    painter.setBrush(hourColor);

    painter.save();
    painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
    painter.drawConvexPolygon(hourHand, 4);
    painter.restore();
    painter.setPen(hourColor);

    for (int i = 0; i < 12; ++i)
    {
        painter.drawLine(88, 0, 96, 0);
        painter.rotate(30.0);
    }

    painter.setPen(Qt::NoPen);
    painter.setBrush(minuteColor);

    painter.save();
    painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
    painter.drawConvexPolygon(minuteHand, 4);
    painter.restore();
    painter.setPen(minuteColor);

    for (int j = 0; j < 60; ++j)
    {
        if ((j % 5) != 0)
            painter.drawLine(92, 0, 96, 0);
        painter.rotate(6.0);
    }

    painter.setPen(Qt::NoPen);
    painter.setBrush(secondColor);


    painter.save();

    cycle = floor(time.msec()/100.0);
    if(time.msec() % 100 > 50)
    {
        cycle++;
    }
    //     QTextStream cout(stdout);
    //    cout << "cycle " + QString::number(cycle) +", " + QString::number(time.msec()) +", " +  QString::number(time.msec()/100.0) + ", " + QString::number(floor(time.msec()/100.0))+ ", " + QString::number(ceil(time.msec()/100.0));
    painter.rotate((time.second() * 6.0) + (cycle * 0.6));
//    painter.drawConvexPolygon(secondHand, 3);
    painter.restore();

    painter.setPen(secondColor);
}
